package csel.controller.listeners;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import csel.controller.decoders.EventDecoder;
import csel.controller.decoders.KeyEventDecoder;
import csel.controller.dispatchers.AbstractDispatcher;
import csel.controller.factories.*;

/**
 * Reasons for Existence: to interpret key presses and create appropriate
 * command objects</br> Team Members Responsible</br> Implementation: Nik,
 * Tait</br> Testing: Nik, Tait</br>
 * 
 * @author Nikolas Wolfe
 */
public class KeyboardListener implements KeyListener
{
	private EventDecoder eventDecoder;
	private KeyEvent keyEvent;
	private String stringKeyEvent;
	private Thread worker;

	//constructor
	public KeyboardListener(AbstractDispatcher modelDispatcher,
			AbstractDispatcher viewDispatcher,
			ModelCommandFactory modelCommandFactory,
			ViewCommandFactory viewCommandFactory)
	{
		// Constructs an appropriate KeyEventDecoder
		this.eventDecoder = new KeyEventDecoder(this, modelDispatcher,
				viewDispatcher, modelCommandFactory, viewCommandFactory);
	}

	//notifies the decoder that a key was pressed
	public void keyPressed(KeyEvent e)
	{
		synchronized (eventDecoder)
		{
			this.keyEvent = e;
			stringKeyEvent = "p " + e.getKeyChar();
			eventDecoder.notify();
		}
	}

	//notifies the decoder that a key was released
	public void keyReleased(KeyEvent e)
	{
		synchronized (eventDecoder)
		{
			this.keyEvent = e;
			stringKeyEvent = "r " + e.getKeyChar();
			eventDecoder.notify();
		}
	}
	
	//required by superclass
	public void keyTyped(KeyEvent e)
	{
		// DON'T DO A DAMN FUCKING THING
	}

	//starts the thread to recieve key events
	public void startWorker()
	{
		worker = new Thread(eventDecoder);
		worker.start();
	}
	
	// this kills the thread so there won't be any leakage
	public void killWorker()
	{
		worker.interrupt();
		System.out.println("[CONTROLLER] Worker thread terminated! ");
	}

	//returns the string used by the parser to determine the key press
	public String getStringEvent()
	{
		return stringKeyEvent;
	}
	
	//returns the keyEvent
	public KeyEvent getKeyEvent()
	{
		return keyEvent;
	}

	//simple toString
	public String toString()
	{
		return this.getClass().getSimpleName();
	}
	
	/*
	 * -------------
	 * TESTING ONLY
	 * -------------
	 */
	public EventDecoder getEventDecoder()
	{
		return eventDecoder;
	}
}
